package com.training.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.training.dao.EmployeeDAO;
import com.training.dto.Employee;
import com.training.exceptions.TMSSystemException;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public void init(ServletConfig config) throws ServletException {

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String userName = request.getParameter("userName").trim();
		String password = request.getParameter("passwordIn");

		EmployeeDAO employeeDAO = new EmployeeDAO();

		try {

			Employee employee = employeeDAO.isValidUser(userName, password);
			if (employee != null)

			{
				HttpSession httpSession = request.getSession();
				httpSession.setMaxInactiveInterval(5000);
				httpSession.setAttribute("employee", employee);

				RequestDispatcher dispatcher = request
						.getRequestDispatcher("welcome.jsp");
				dispatcher.forward(request, response);

			} else {
				response.sendRedirect("fail.html");
			}

		} catch (TMSSystemException e) {
			response.sendError(response.SC_INTERNAL_SERVER_ERROR);
		}

	}

}
